package smb.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import smb.util.SmbUtil;

/**
 * Servlet implementation class DownloadSmbFile
 */
@WebServlet(description = "下载文件", urlPatterns = { "/download" })
public class DownloadSmbFile extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String path = request.getParameter("path");
		if (null == path) {
			throw new ServletException("require download file path");
		}
		path = new String(path.getBytes("ISO-8859-1"), "utf-8");
		path = SmbUtil.BasePath + path;
		SmbFile smbFile = new SmbFile(path);
		if (!smbFile.exists()) {
			throw new ServletException("download file not exists");
		}
		if (smbFile.isDirectory()) {
			throw new ServletException("download is not a file");
		}
		System.out.println("download:" + smbFile.getName());
		response.setCharacterEncoding("utf-8");

		response.setHeader("Content-Disposition",
				"attachment; filename=" + new String(smbFile.getName().getBytes("utf-8"), "ISO-8859-1") + "");
		// 获取响应报文输出流对象
		ServletOutputStream out = response.getOutputStream();
		int length = smbFile.getContentLength();// 得到文件的大小
		byte buffer[] = new byte[length];
		SmbFileInputStream in = new SmbFileInputStream(smbFile);
		// 建立smb文件输入流
		while ((in.read(buffer)) != -1) {

			out.write(buffer);
			System.out.println(buffer.length);
		}
		in.close();

		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
